package com.zhfi.dataapply.schedule.writer.market;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhfi.dataapply.entity.data.po.market.ShareholderTotalPO;
import com.zhfi.dataapply.entity.data.vo.market.MarketShareholderVO;
import com.zhfi.dataapply.mapper.market.MarketShareholderMapper;
import com.zhfi.dataapply.mapper.market.ShareholderTotalMapper;
import com.zhfi.dataapply.util.BaseMapperUtil;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MarketShareholderWriter implements ItemWriter<MarketShareholderVO> {

    @Autowired
    private MarketShareholderMapper marketShareholderMapper;
    @Autowired
    private ShareholderTotalMapper shareholderTotalMapper;

    @Override
    public void write(List<? extends MarketShareholderVO> list) throws Exception {
        for (MarketShareholderVO vo : list) {
            ShareholderTotalPO shareholderTotalPO = new ShareholderTotalPO();
            BeanUtils.copyProperties(vo, shareholderTotalPO);
            UpdateWrapper<ShareholderTotalPO> updateWrapper = new UpdateWrapper<>();
            Map<String, Object> primaryKeyMap = new HashMap<>();
            primaryKeyMap.put("company_id", shareholderTotalPO.getCompanyId());
            primaryKeyMap.put("publish_date", shareholderTotalPO.getPublishDate());
            updateWrapper.allEq(primaryKeyMap);
            shareholderTotalMapper.update(shareholderTotalPO, updateWrapper);
            vo.getShareHolderList().forEach(po -> {
                po.setCompanyId(vo.getCompanyId());
                po.setPublishDate(vo.getPublishDate());
                BaseMapperUtil.updateOrInsert(marketShareholderMapper, po);
            });
        }
    }
}
